package com.ch6.heartbeat;
 
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;

import com.ch6.Header;
import com.ch6.Message;
import com.ch6.NettyConstant;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
 

/**
 * @author U317076
 *
 */
public class HeartbeatClientHandler extends ChannelInboundHandlerAdapter {

	private volatile ScheduledFuture<?> heartbeat;
	
	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg)
			throws Exception {
		// TODO Auto-generated method stub
		heartbeat=ctx.executor().scheduleAtFixedRate(new HeartbeatClientHandler.HeartbeatTask(ctx), 0, 5000,TimeUnit.MILLISECONDS);

		//ctx.fireChannelRead(msg);
	}
	
	
	/**
	 * heartbeat
	 * @author U317076
	 *
	 */
	private class HeartbeatTask implements Runnable{
		
		private final ChannelHandlerContext ctx;
		
		public HeartbeatTask(ChannelHandlerContext ctx) {
			 this.ctx=ctx;
		}

		@Override
		public void run() {
			 
			 Message message=new Message();
			 Header header=new Header();
 			 header.setType(NettyConstant.MessageType.HEARTBEAT_REQ.value());
			 
			 message.setHeader(header);
             this.ctx.pipeline().writeAndFlush(message);			
			
			System.out.println(">>>>>>heartbeat");
			
		}
		
	}
	
}
